package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.code.RedisCode;
import one.stand.entity.TokenEntity;
import one.stand.entity.excel.CompanyExcelEntity;
import one.stand.enums.AuditStateEnums;
import one.stand.enums.LoginEnum;
import one.stand.model.*;
import one.stand.model.live.CompanyVideoSwtichModel;
import one.stand.request.*;
import one.stand.request.live.SwitchVideoForm;
import one.stand.response.AdminResponse;
import one.stand.response.CompanyAccountResponse;
import one.stand.response.CompanyResponse;
import one.stand.response.VersionResponse;
import one.stand.service.BaseService;
import one.stand.service.CompanyService;
import one.stand.util.DateUtil;
import one.stand.util.ExportDataDTO;
import one.stand.util.Md5Util;
import one.stand.util.OssUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Service
@Transactional
public class CompanyServiceImpl extends BaseService implements CompanyService {

    /**
     * 缓存两小时
     */
    protected final static Integer LOGIN_TIME_LONG = 7000;

    @Autowired
    private OssUtil ossUtil;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<AdminResponse> login(AdminRequest request) {
        log.info("总后台登录：{}", JSON.toJSONString(request));
        if (request == null || StringUtils.isBlank(request.getLoginName()) || StringUtils.isBlank(request.getPassWord())) {
            return ResultModel.fail("请输入管理员账号或密码~！");
        }
        AdminModel model = adminMapper.select(new AdminModel() {{
            setLoginName(request.getLoginName());
        }});
        if (model == null) {
            return ResultModel.fail("登录账号无效~！");
        }
        if (model.getIsDel() == 1) {
            return ResultModel.fail("该公司已被清除~！");
        }
        if (!Md5Util.md5(request.getPassWord()).equals(model.getPassWord())) {
            return ResultModel.fail("登录密码错误~！");
        }
        // 加载菜单列
        List<MenuModel> modelList = menuMapper.selectList(new MenuModel() {{
            setAdminId(model.getAdminId());
        }});
        TokenEntity tokenEntity = createToken(model.getAdminId().longValue());
        tokenEntity.setLoginProgramName(LoginEnum.ADMIN.getCode());
        tokenEntity.setCId(model.getAdminId().longValue());
        tokenEntity.setTourist(model.getTourist());
        tokenEntity.setId(model.getAdminId().longValue());
        redisUtil.set(RedisCode.getAdminToken(tokenEntity.getToken()), tokenEntity, LOGIN_TIME_LONG, TimeUnit.SECONDS);
        AdminResponse response = new AdminResponse();
        BeanUtils.copyProperties(model, response);
        response.setList(modelList);
        response.setToken(tokenEntity.getToken());
        response.setPassWord(null);
        response.setOssUrl(ossUtil.getOssUrl());
        return ResultModel.success(response);
    }

    @Override
    @Transactional(propagation = Propagation.NEVER)
    public ResultModel<Boolean> checkingToken(String token) {
        if (StringUtils.isBlank(token)) {
            return ResultModel.success(false);
        }
        TokenEntity tokenEntity = redisUtil.get(RedisCode.getAdminToken(token));
        if (tokenEntity == null) {
            return ResultModel.success(false);
        }
        // 重新赋值,为redis重置过期时间
        redisUtil.set(RedisCode.getAdminToken(token), tokenEntity, LOGIN_TIME_LONG, TimeUnit.SECONDS);
        return ResultModel.success(true);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, Object>> selectAdminRecordList(AdminRecordRequest request) {
        log.info("查询管理员操作记录列表：{}", JSON.toJSONString(request));
        AdminRecordModel model = new AdminRecordModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<AdminRecordModel> list = adminRecordMapper.select(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<AdminRecordModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    /**
     * 审核公司
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> auditCompany(CompanyRequest request) {
        log.info("审核公司参数：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getCompanyId() == null) {
            return ResultModel.checkParamFail("companyId为空");
        }
        CompanyModel model = new CompanyModel();
        model.setCompanyId(request.getCompanyId());
        model.setAuditState(request.getAuditState());
        model.setAuditRemark(request.getAuditRemark());
        int r = companyMapper.updateByPrimaryKeySelective(model);
        if (r > 0) {
            // 公司审核成功
            if (request.getAuditState().equals(AuditStateEnums.APPLY_SUCCESS.getCode())) {

            }
            return ResultModel.success(true);
        }
        return ResultModel.fail();
    }

    /**
     * 公司购买名片服务数
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultModel<Boolean> addCompanyService(CompanyServiceRequest request) {
        log.info("总后台公司配置参数：{}", request.toString());
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getCompanyId() == null) {
            return ResultModel.checkParamFail("companyId为空");
        }
        // 设置企业的购买版本，代理权限和代理价格
        ResultModel<Boolean> resultModel = configureAgen(new CompanyRequest() {{
            setCompanyId(request.getCompanyId());
            setCompanyType(request.getCompanyType());
            setIsAgent(request.getIsAgent());
            setAgentMoney(request.getAgentMoney());
            setId(request.getId());
        }});
        if (!resultModel.isSuccess()) {
            return resultModel;
        }
        if (!StringUtils.isBlank(request.getEndTime())) {
            // 公司购买名片服务数
            if (request.getPurchaseNum() != null && request.getPurchaseNum() > 0) {
                return configureCompanyService(new CompanyServiceRequest() {{
                    setId(request.getId());
                    setCompanyId(request.getCompanyId());
                    setPayNum(request.getPayNum());
                    setPurchaseNum(request.getPurchaseNum());
                    setCurrentNum(request.getPurchaseNum());
                    setEndTime(request.getEndTime());
                }});
            } else {
                // 修改公司名片服到期时间
                return updateCompanyServiceEndTime(new CompanyServiceRequest() {{
                    setId(request.getId());
                    setCompanyId(request.getCompanyId());
                    setEndTime(request.getEndTime());
                }});
            }
        }
        return resultModel;
    }

    /**
     * 设置企业购买版本，代理权限和代理价格
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultModel<Boolean> configureAgen(CompanyRequest request) {
        log.info("设置企业购买版本，代理权限和代理价格：{}", JSON.toJSONString(request));
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.checkParamFail();
        } else if (request.getCompanyId() == null) {
            return ResultModel.checkParamFail("companyId为空");
        }
        Integer isAgent = companyMapper.getCompanyIsAgent(request.getCompanyId());
        CompanyModel model = new CompanyModel();
        model.setCompanyId(request.getCompanyId());
        model.setAgentMoney(request.getAgentMoney());
        model.setIsAgent(request.getIsAgent());
        model.setCompanyType(request.getCompanyType());
        companyMapper.updateByPrimaryKeySelective(model);
        // 判断是否改变公司代理权限，有改变就添加操作记录，没有改变就直接返回
        if (isAgent.equals(request.getIsAgent())) {
            return ResultModel.success();
        }
        AdminRecordModel adminRecordModel = new AdminRecordModel();
        adminRecordModel.setAdminId(request.getId().intValue());
        adminRecordModel.setCompanyId(request.getCompanyId());
        if (request.getIsAgent() == 0) {
            adminRecordModel.setContent("撤销代理商标示");
        } else {
            adminRecordModel.setContent("设置存为代理商，代理价格:" + money(request.getAgentMoney()) + "元");
        }
        adminRecordModel.setOperationId(2);
        adminRecordModel.setCreateTime(currentDate());
        // 增加操作记录
        adminRecordMapper.insertSelective(adminRecordModel);
        return ResultModel.success();
    }

    private String formatDate(Date date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }

    private Date parseDate(String str) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.parse(str);
    }

    private String formatYMDDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }

    /**
     * 设置公司购买名片服务数
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> configureCompanyService(CompanyServiceRequest request) {
        log.info("公司购买名片服务数参数：{}", JSON.toJSONString(request));
        // 查询公司购买服务数
        CompanyServiceModel model = companyServiceMapper.selectCompanyService(new CompanyServiceModel() {{
            setCompanyId(request.getCompanyId());
            setType(1);
        }});
        try {
            CompanyServiceModel companyServiceModel = new CompanyServiceModel();
            // 公司id
            companyServiceModel.setCompanyId(request.getCompanyId());
            // 1,使用，2购买，3员工退出
            companyServiceModel.setPurchaseType(2);
            // 1,当前,0记录
            companyServiceModel.setType(1);
            // 支付金额
            companyServiceModel.setPayNum(request.getPayNum());
            // 本次操作数量
            companyServiceModel.setPurchaseNum(request.getPurchaseNum());
            // 当前总购买数
            companyServiceModel.setCurrentNum(request.getPurchaseNum());
            // 创建时间
            companyServiceModel.setCreateTime(currentDate());
            // 到期时间
            companyServiceModel.setEndTime(parseDate(request.getEndTime() + " 23:59:59"));
            if (model == null) {
                // 状态：0未授权，1以授权（花钱购买服务）
                if (request.getPayNum() == null || request.getPayNum() <= 0) {
                    companyServiceModel.setServiceState(0);
                } else {
                    companyServiceModel.setServiceState(1);
                }
                // 操作前可用数量
                companyServiceModel.setHistoryNum(0);
                // 当前可用数量
                companyServiceModel.setAvailableNum(request.getPurchaseNum());
                companyServiceMapper.insertSelective(companyServiceModel);
            } else {
                // 判断到期时间
                if (!compareDate(parseDate(request.getEndTime() + " 23:59:59"), model.getEndTime())) {
                    return ResultModel.fail("到期时间不能小于:" + formatYMDDate(model.getEndTime()));
                }
                // 状态：0未授权，1以授权（花钱购买服务）
                boolean fal = (model.getServiceState() != null && model.getServiceState() == 1) || (request.getPayNum() != null && request.getPayNum() > 0);
                if (fal) {
                    companyServiceModel.setServiceState(1);
                } else {
                    companyServiceModel.setServiceState(0);
                }
                // 操作前可用数量
                companyServiceModel.setHistoryNum(model.getAvailableNum());
                // 当前可用数量(本次购买总数-（上次购买数量-上次剩余数量）)
                companyServiceModel.setAvailableNum(request.getPurchaseNum() - (model.getCurrentNum() - model.getAvailableNum()));
                companyServiceMapper.insertSelective(companyServiceModel);
                // 修改之前的名片服务记录表状态为记录
                companyServiceMapper.updateByPrimaryKeySelective(new CompanyServiceModel() {{
                    setType(0);
                    setServiceId(model.getServiceId());
                }});
            }
            // 增加操作记录
            adminRecordMapper.insertSelective(new AdminRecordModel() {{
                setAdminId(request.getId().intValue());
                setCompanyId(request.getCompanyId());
                StringBuffer content = new StringBuffer("购买总数：").append(request.getPurchaseNum());
                if (request.getPayNum() != null && request.getPayNum() > 0) {
                    content.append("；支付金额：").append(money(request.getPayNum())).append("元");
                }
                setContent(content.append("；到期时间：").append(request.getEndTime()).toString());
                setOperationId(1);
                setCreateTime(currentDate());
            }});
            return ResultModel.success(true);
        } catch (ParseException e) {
            log.error("设置公司购买名片服务数[异常]", e);
            return ResultModel.fail("设置购买名片服务数[异常]" + e.getMessage());
        } catch (Exception e) {
            log.error("设置购买名片服务数[异常]", e);
            return ResultModel.fail("设置购买名片服务数[异常]" + e.getMessage());
        }
    }

    /**
     * 修改公司名片服务到期时间
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> updateCompanyServiceEndTime(CompanyServiceRequest request) {
        log.info("修改公司名片服务到期时间：{}", JSON.toJSONString(request));
        // 查询公司购买服务数
        CompanyServiceModel model = companyServiceMapper.selectCompanyService(new CompanyServiceModel() {{
            setCompanyId(request.getCompanyId());
            setType(1);
        }});
        try {
            // 判断到期时间
            if (!compareDate(parseDate(request.getEndTime() + " 23:59:59"), model.getEndTime())) {
                return ResultModel.fail("到期时间不能小于:" + formatYMDDate(model.getEndTime()));
            }
            CompanyServiceModel companyServiceModel = new CompanyServiceModel();
            companyServiceModel.setEndTime(parseDate(request.getEndTime() + " 23:59:59"));
            companyServiceModel.setServiceId(model.getServiceId());
            companyServiceMapper.updateByPrimaryKeySelective(companyServiceModel);
            // 增加操作记录
            adminRecordMapper.insertSelective(new AdminRecordModel() {{
                setAdminId(request.getId().intValue());
                setCompanyId(request.getCompanyId());
                setContent(new StringBuffer("设置到期时间：").append(request.getEndTime()).toString());
                setOperationId(1);
                setCreateTime(currentDate());
            }});
            return ResultModel.success(true);
        } catch (ParseException e) {
            log.error("修改公司名片服务到期时间[异常]", e);
            return ResultModel.fail("修改公司名片服务到期时间[异常]");
        } catch (Exception e) {
            log.error("修改公司名片服务[异常]", e);
            return ResultModel.fail("修改公司名片服务[异常]: " + e.getMessage());
        }
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, Object>> selectAdminList(AdminRequest request) {
        log.info("查询管理员列表：{}", JSON.toJSONString(request));
        AdminModel model = new AdminModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<AdminModel> list = adminMapper.selectList(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<AdminModel> modelList = new ArrayList<>();
        list.forEach(obj -> {
            {
                // 加载菜单列
                List<MenuModel> menuModelList = menuMapper.select(new MenuModel() {{
                    setAdminId(obj.getAdminId());
                }});
                obj.setModelList(menuModelList);
                modelList.add(obj);
            }
        });
        PageInfo<AdminModel> pageInfo = new PageInfo(modelList);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultModel<Boolean> delAdmin(AdminRequest request) {
        log.info("删除管理员：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getAdminId() == null) {
            return ResultModel.checkParamFail("adminId为空");
        } else if (request.getIsDel() == null) {
            return ResultModel.checkParamFail("isDel为空");
        }
        adminMapper.updateByPrimaryKeySelective(new AdminModel() {{
            setAdminId(request.getAdminId());
            setIsDel(request.getIsDel());
        }});
        return ResultModel.success(true);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultModel<Boolean> inserAdminRole(AdminRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getAdminId() == null) {
            return ResultModel.checkParamFail("adminId为空");
        } else if (request.getRoleIds() == null) {
//            return ResultModel.checkParamFail("roleIds为空");
            log.info("roleIds为空,删除用户权限:{}",request.getAdminId());
        }
        // 删除以前的权限
        adminMapper.delAdminMenu(request.getAdminId());
        if(request.getRoleIds() != null && request.getRoleIds().length > 0){
            List<AdminMenuModel> list = new ArrayList<>();
            for (Integer roid : request.getRoleIds()) {
                AdminMenuModel model = new AdminMenuModel();
                model.setAdminId(request.getAdminId());
                model.setMenuId(roid);
                list.add(model);
            }
            adminMapper.insertAdminMenu(list);
        }
        return ResultModel.success(true);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<List<MenuModel>> selectMenuList() {
        List<MenuModel> list = menuMapper.selectAllList(new MenuModel() {{
        }});
        return ResultModel.success(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Integer> saveAdmin(AdminRequest request) {
        log.info("添加、修改管理员参数：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (StringUtils.isBlank(request.getLoginName())) {
            return ResultModel.fail("请输入管理员账号~！");
        }
        AdminModel adminModel = adminMapper.select(new AdminModel() {{
            setLoginName(request.getLoginName());
            setMyAdminId(request.getAdminId());
        }});
        if (adminModel != null) {
            return ResultModel.fail("管理员账号重复~！");
        }
        AdminModel model = new AdminModel();
        BeanUtils.copyProperties(request, model);
        if (request.getAdminId() == null) {
            if (StringUtils.isBlank(request.getPassWord())) {
                return ResultModel.fail("请输入管理员密码~！");
            }
            model.setPassWord(Md5Util.md5(request.getPassWord()));
            model.setCreateTime(currentDate());
            model.setIsDel(0);
            adminMapper.insertSelective(model);
            return ResultModel.success(model.getAdminId());
        }
        if (!StringUtils.isBlank(request.getPassWord())) {
            model.setPassWord(Md5Util.md5(request.getPassWord()));
        }
        adminMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(model.getAdminId());
    }

    /**
     * 企业首页数据统计
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<FinanceModel> indexData(FinanceRequest request) {
        log.info("企业首页数据统计参数：{}", JSON.toJSONString(request));
        FinanceModel model = new FinanceModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        FinanceModel financeModel = companyMapper.selectAdminIndexCount(model);
        if (financeModel == null) {
            return ResultModel.noData();
        }
        return ResultModel.success(financeModel);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, List<Map<String, Object>>>> newCountList(FinanceRequest request) {
        log.info("企业首页数据统计折线图参数：{}", JSON.toJSONString(request));
        FinanceModel model = new FinanceModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        List<Map<String, Object>> newCustomerList = companyMapper.newCustomerList(model);
        List<Map<String, Object>> newCompanyList = companyMapper.newCompanyList(model);
        Map<String, List<Map<String, Object>>> map = new HashMap<>(2);
        map.put("newCustomerList", newCustomerList);
        map.put("newCompanyList", newCompanyList);
        return ResultModel.success(map);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, Object>> dataCenter(FinanceRequest request) {
        log.info("数据中心-数据概况参数：{}", JSON.toJSONString(request));
        FinanceModel model = new FinanceModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        Map<String, Object> map = companyMapper.dataCenter(model);
        return ResultModel.success(map);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<List<Map<String, Object>>> newUserCountList(FinanceRequest request) {
        log.info("数据中心-用户增长情况参数：{}", JSON.toJSONString(request));
        FinanceModel model = new FinanceModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        List<Map<String, Object>> list = companyMapper.newUserCountList(model);
        return ResultModel.success(list);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<List<Map<String, Object>>> userUseCountList(FinanceRequest request) {
        log.info("数据中心-使用人数增长情况参数：{}", JSON.toJSONString(request));
        FinanceModel model = new FinanceModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        List<Map<String, Object>> list = companyMapper.userUseCountList(model);
        return ResultModel.success(list);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<List<Map<String, Object>>> userSexCount(FinanceRequest request) {
        log.info("用户画像-性别分布：{}", JSON.toJSONString(request));
        FinanceModel model = new FinanceModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        List<Map<String, Object>> map = companyMapper.userSexCount(model);
        return ResultModel.success(map);
    }

    /**
     * 查询企业列表
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, Object>> selectCompanyList(CompanyRequest request) {
        log.info("查询企业列表参数：{}", JSON.toJSONString(request));
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyModel> list = companyMapper.selectCompanyList(new CompanyModel() {{
            setEnterpriseType(request.getEnterpriseType());
            setCompanyName(request.getCompanyName());
        }});
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<CompanyModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Boolean> selectCompanyListExport(CompanyRequest request) {
        log.info("导出企业列表参数：{}", JSON.toJSONString(request));
        List<CompanyModel> list = companyMapper.selectCompanyList(new CompanyModel() {{
            setEnterpriseType(request.getEnterpriseType());
            setCompanyName(request.getCompanyName());
        }});
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        List<CompanyExcelEntity> excelEntities = new ArrayList<>();
        list.forEach(model -> {
            {
                CompanyExcelEntity excelEntity = new CompanyExcelEntity();
                BeanUtils.copyProperties(model, excelEntity);
                if (model.getCreateTime() != null) {
                    excelEntity.setCreateTime(formatDate(model.getCreateTime()));
                }
                if (model.getEndTime() != null) {
                    excelEntity.setEndTime(formatDate(model.getEndTime()));
                }
                excelEntities.add(excelEntity);
            }
        });
        ExportDataDTO exportDataDTO = new ExportDataDTO();
        exportDataDTO.setSheetName("企业列表");
        exportDataDTO.setFileName("企业列表");
        exportDataDTO.setTitle("企业列表");
        exportDataDTO.setDataList(excelEntities);
        return ResultModel.success(exportDataDTO);
    }

    /**
     * 查询企业信息
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<CompanyResponse> getCompanyInfo(CompanyRequest request) {
        log.info("查询企业信息参数：{}", JSON.toJSONString(request));
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.noData();
        }
        CompanyModel model = companyMapper.getAdminCompanyInfo(new CompanyModel() {{
            setCompanyId(request.getCompanyId());
        }});
        CompanyResponse response = new CompanyResponse();
        if (model != null) {
            BeanUtils.copyProperties(model, response);
        }
        return ResultModel.success(response);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, Object>> selectAgentCompanyList(CompanyRequest request) {
        log.info("查询代理商企业下公司的信息参数：{}", JSON.toJSONString(request));
        if (request == null || request.getCompanyId() == null) {
            return ResultModel.noData();
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyModel> list = companyMapper.selectAgentCompanyList(new CompanyModel() {{
            setCompanyName(request.getCompanyName());
            setAgentCompanyId(request.getCompanyId());
        }});
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<CompanyModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, Object>> appletCodeManage(VersionRequest request) {
        log.info("查询小程序代码管理列表参数：{}", JSON.toJSONString(request));
        VersionModel model = new VersionModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<VersionModel> list = versionMapper.selectList(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<CompanyModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<VersionResponse> appletCodeManageInfo(VersionRequest request) {
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (request.getVersionId() == null) {
            return ResultModel.checkParamFail("versionId为空");
        }
        VersionModel model = versionMapper.selectByPrimaryKey(request.getVersionId());
        VersionResponse response = new VersionResponse();
        if (model != null) {
            BeanUtils.copyProperties(model, response);
        }
        return ResultModel.success(response);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultModel<Boolean> addVersionInfo(VersionRequest request) {
        log.info("添加版本号：{}", JSON.toJSONString(request));
        if (request == null) {
            return ResultModel.checkParamFail();
        } else if (StringUtils.isBlank(request.getAppId())) {
            return ResultModel.checkParamFail("appId为空");
        } else if (StringUtils.isBlank(request.getTemplateId())) {
            return ResultModel.checkParamFail("templateId为空");
        } else if (StringUtils.isBlank(request.getVersionNum())) {
            return ResultModel.checkParamFail("versionNum为空");
        }
        Integer versionType = versionMapper.selectCompanyAccount(request.getAppId());
        if (versionType == null) {
            return ResultModel.fail("AppId异常，请稍后重试~！");
        }
        if (versionMapper.addVerification(new VersionModel() {{
            setVersionType(versionType);
            setTemplateId(request.getTemplateId());
            setVersionNum(request.getVersionNum());
        }}) > 0) {
            return ResultModel.fail("版本或者模板重复");
        }

        VersionModel model = new VersionModel();
        BeanUtils.copyProperties(request, model);
        model.setCreateTime(currentDate());
        model.setIsDel(0);
        model.setVersionState(1);
        model.setVersionType(versionType);
        versionMapper.insertSelective(model);
        return ResultModel.success(true);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<List<String>> selectAppId(Integer versionId) {
        List<String> list = versionMapper.selectAppId(versionId);
        return ResultModel.success(list);
    }

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultModel<Map<String, Object>> selectCompanyAccountList(CompanyAccountRequest request) {
        log.info("查询公司账号列表：{}", JSON.toJSONString(request));
        CompanyAccountModel model = new CompanyAccountModel();
        if (request != null) {
            BeanUtils.copyProperties(request, model);
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyAccountResponse> list = companyAccountMapper.selectCompanyAccountList(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<CompanyAccountResponse> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public ResultModel<Boolean> updateAgentCompanyId(CompanyRequest request) {
        if (request == null || request.getCompanyId() == null || request.getAgentCompanyId() == null) {
            return ResultModel.checkParamFail();
        }
        Integer agentCompanyId = companyMapper.getAgentCompanyId(request.getAgentCompanyId());
        if (agentCompanyId == null || agentCompanyId <= 0) {
            return ResultModel.fail("无效的代理商ID~！");
        }
        CompanyModel model = new CompanyModel();
        model.setCompanyId(request.getCompanyId());
        model.setAgentCompanyId(request.getAgentCompanyId());
        companyMapper.updateByPrimaryKeySelective(model);
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Map<String, Object>> findCompanySwtich(CompanyRequest request) {
        log.info("查询企业短视频开关参数：{}", JSON.toJSONString(request));
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<CompanyVideoSwtichModel> list = companyMapper.findCompanySwtich(new CompanyModel() {{
            setCompanyName(request.getCompanyName());
        }});
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<CompanyVideoSwtichModel> pageInfo = new PageInfo(list);
        Map<String, Object> map = new HashMap<>(1);
        map.put("pageInfo", pageInfo);
        return ResultModel.success(map);
    }

    @Override
    public ResultModel<Boolean> switchVideo(SwitchVideoForm request) {
        VideoSwtichModel videoSwtichModel = this.videoSwtichMapper.selectByCompanyId(request.getCompanyId().intValue());
        if(videoSwtichModel != null){
            videoSwtichModel.setState(request.getSwitchVideo());
            this.videoSwtichMapper.updateByPrimaryKey(videoSwtichModel);
            return ResultModel.success();
        }else{
            videoSwtichModel = new VideoSwtichModel();
            videoSwtichModel.setCompanyId(request.getCompanyId().intValue());
            videoSwtichModel.setState(request.getSwitchVideo());
            videoSwtichModel.setCreateTime(DateUtil.now());
            this.videoSwtichMapper.insert(videoSwtichModel);
            return ResultModel.success();
        }
    }

    @Override
    public ResultModel<Boolean> updateVideoSize(SwitchVideoForm request) {
        VideoSwtichModel videoSwtichModel = this.videoSwtichMapper.selectByCompanyId(request.getCompanyId().intValue());
        if(videoSwtichModel != null){
            videoSwtichModel.setVideoSize(request.getVideoSize());
            this.videoSwtichMapper.updateByPrimaryKeySelective(videoSwtichModel);
            return ResultModel.success();
        }else{
            videoSwtichModel = new VideoSwtichModel();
            videoSwtichModel.setCompanyId(request.getCompanyId().intValue());
            videoSwtichModel.setState(false);
            videoSwtichModel.setCreateTime(DateUtil.now());
            videoSwtichModel.setVideoSize(request.getVideoSize());

            this.videoSwtichMapper.insert(videoSwtichModel);
            return ResultModel.success();
        }
    }
}
